<template>
  <div class="wrapper">
    <div class="content">
      <el-form :inline="true">
        <el-form-item label="订单号">
          <el-input type="text" placeholder="订单号" v-model="orderNo"></el-input>
        </el-form-item>
        <el-form-item label="原始订单号">
          <el-input type="text" placeholder="原始订单号" v-model="originOrderNo"></el-input>
        </el-form-item>
        <el-form-item label="平台：">
          <el-select style="width: 150px;" clearable v-model="platId" placeholder="请选择推广平台">
            <el-option v-for="item in platList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="销售时间：">
          <el-date-picker
            v-model="datarange"
            type="daterange"
            value-format="yyyy-MM-dd"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <br>
        <el-form-item style="position: relative"> 
          <el-button type="primary" @click="searchItem(true)">查询</el-button>
          <el-button v-if="isManager || isTeamer" type="primary" @click="openDialog()">录入</el-button>
          <el-button type="primary" @click="exportExcel()">导出</el-button>
          <el-button v-if="isManager || isTeamer" type="primary">导入</el-button>
          <input type="file" class="file-upload-btn" @change="uploadFile($event)">
        </el-form-item>
        <el-form-item style="position: relative"> 
          <el-button v-if="isManager" type="primary" @click="updateB2C()">立即更新B2C订单</el-button>
        </el-form-item>
      </el-form>
      <div>
        <el-table :height="tableHeight" :data="tableData"  border style="width: 100%;overflow-x: auto;" >
          <el-table-column label="订单号" fixed prop="orderNo" min-width="180" align="center"></el-table-column>
          <el-table-column label="原始订单号" prop="originOrderNo" min-width="180" align="center"></el-table-column>
          <el-table-column label="销售平台" prop="platId" min-width="180" align="center">
            <template slot-scope="scope">
              {{getPlat(scope.row.platId)}}
            </template>
          </el-table-column>
          <el-table-column label="折前销售金额($)" prop="saleValueBd" min-width="180" align="center"></el-table-column>
          <el-table-column label="折后销售金额($)" prop="saleValue" min-width="180" align="center"></el-table-column>
          <el-table-column label="折前原始货币金额($)" prop="originSaleValueBd" min-width="180" align="center"></el-table-column>
          <el-table-column label="折后原始货币金额($)" prop="originSaleValue" min-width="180" align="center"></el-table-column>
          <el-table-column label="结算币种" prop="currencyType" min-width="100" align="center"></el-table-column>
          <el-table-column label="类型" prop="type" min-width="100" align="center"></el-table-column>
          <el-table-column label="销售时间" prop="originSaleDate" min-width="180" align="center"></el-table-column>
          <el-table-column label="订单收货国家" prop="countryName" min-width="180" align="center"></el-table-column>
          <el-table-column label="操作人" prop="opUser" min-width="180" align="center"></el-table-column>
          <el-table-column label="操作时间" prop="opDate" min-width="180" align="center"></el-table-column>
          <el-table-column label="备注" prop="remark" min-width="180" align="center"></el-table-column>
          <!-- <el-table-column label="操作" min-width="100" align="center">
            <template slot-scope="scope">
              <el-button @click="openDialog(scope.row)" type="text" size="small">编辑</el-button>
              <el-button @click="removeItem(scope.row.id)" type="text" size="small">删除</el-button>
            </template>
          </el-table-column> -->
        </el-table>
      </div>
      <el-pagination
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="page"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        :total="totalPage"
        layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>
    </div>
    <el-dialog :fullscreen="true" :visible.sync="customerDialog" :show-close="false">
      <div slot="title">
        <h2 style="text-align:center;margin-bottom:0;">录入B2C订单</h2>
      </div>
      <div class="form-wrapper">
        <el-button type="info" class="back-btn" icon="el-icon-back" circle @click="customerDialog = false;"></el-button>
        <el-form ref="form" :model="customForm" label-width="200px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item style="font-weight: bold;" label="管家订单号">
                <el-input v-model="customForm.orderNo"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item style="font-weight: bold;" label="销售平台">
                 <el-select v-model="customForm.platId" placeholder="请选择销售平台">
                  <el-option v-for="item in platList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item style="font-weight: bold;" label="折前销售金额">
                <el-input v-model="customForm.saleValueBd"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item style="font-weight: bold;" label="折后销售金额">
                <el-input v-model="customForm.saleValue"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item style="font-weight: bold;" label="结算币种">
                <el-select ref="labelSelected" :filterable="true" v-model="customForm.currencyType" placeholder="请选择币种">
                  <el-option v-for="item in currencyList" :key="item.code" :label="item.name" :value="item.code"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item style="font-weight: bold;" label="订单状态">
                <el-select ref="labelSelected" :filterable="true" v-model="customForm.status" placeholder="请选择状态">
                  <el-option v-for="item in orderStatusList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item style="font-weight: bold;" label="国家">
                <el-select ref="labelSelected" :filterable="true" v-model="customForm.countryCode" placeholder="请选择国家">
                  <el-option v-for="item in countryList" :key="item.code" :label="item.name" :value="item.code"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item style="font-weight: bold;" label="销售日期">
                <el-date-picker type="date" value-format="yyyy-MM-dd" placeholder="选择日期" v-model="customForm.saleDate" style="width: 100%;"></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item style="font-weight: bold;" label="备注">
                <el-input v-model="customForm.remark"></el-input>              
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item>
            <el-button type="primary" @click="saveForm">录入</el-button>
            <el-button @click="customerDialog = false;">关闭</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import dingMixin from  '@/mixins/ding'
  import formUtil from '@/utils/formUtil'
  import DatePhase from  '@/components/sale/date-phase'

  export default {
    data () {
      return {
        pageSize: 10,
        page:1,
        totalPage: 0,
        datarange: '',
        countryData: [],
        tableData: [],
        platId: '',
        originOrderNo: '',
        orderNo: '',
        customForm: {
          orderNo: '',
          platId: '',
          saleValueBd: '',
          saleValue: '',
          currencyType: '',
          status: '',
          remark: '',
          saleDate: '',
          countryCode: '',
        },
        formVerify: {
          orderNo: '请输入管家订单号',
          platId: '请选择销售平台',
          saleValueBd: '请输入折前销售金额',
          saleValue: '请输入折后销售金额',
          currencyType: '请选择结算币种',
          status: '请选择订单状态',
          countryCode: '请选择国家',
          saleDate: '请选择销售日期'
        },
        customerDialog: false,
        platList: [],
        orderStatusList: [{
          id: 11,
          name: '完成'
        },{
          id: 1,
          name: '已售'
        },{
          id: 0,
          name: '预售'
        },{
          id: -1,
          name: '退款'
        },{
          id: -2,
          name: '无效订单'
        }],
        countryList: [],
        currencyList: [],
        isTeamer: false,
        tableHeight: window.tableHeight
      }
    },
    computed: {
      isManager() {
        return this.userInfo.roleIdList && this.userInfo.roleIdList.includes('1265175017173348354')
      }
    },
    components: {
      DatePhase
    },
    activated() {
      this.tableHeight = document.documentElement['clientHeight'] - 330
      window.onresize = () => {
        this.tableHeight = document.documentElement['clientHeight'] - 330
      }
    },
    mixins: [dingMixin],
    async mounted(){
      let data = await this.$httpN.postQ('mpb/plat/tree', {isPo: 0});
      data.forEach((item) => {
        let pArr = item.manager.split(',')
        let pArr2 = item.members.split(',')
        if(pArr.includes(this.userInfo.dingId) || pArr2.includes(this.userInfo.dingId)) this.isTeamer = true;
        if(item.children) {
          item.children.forEach((child) => {
            if(child.category === 'b2c') {
              let cArr = child.manager.split(',')
              let cArr2 = child.members.split(',')
              if(cArr.includes(this.userInfo.dingId) || cArr2.includes(this.userInfo.dingId)) this.isTeamer = true;
              this.platList.push(child)
            }
          })
        }else {
          if(item.category === 'b2c'){
            this.platList.push(item)
          }
        }
      })
      this.countryList = await this.$httpN.postQ('mpb/market/listCountry', {level: '', query: ''}, false);
      this.currencyList = await this.$httpN.postQ('mpb/currency/list', {}, false);
      this.searchItem(true);
    },
    methods: {
      getPlat(id) {
        let result = this.platList.filter(item => item.id === id);
        return result.length > 0 ? result[0].name: ''
      },
      openDialog(item) {
        if(item) {
          let editData = formUtil.deepCopy(item);
          this.customForm = editData;
        }else{
          formUtil.resetData(this.customForm);
          this.customForm.status = '';
        }
        this.customerDialog = true;
      },
      async searchItem(init) {
        if(init) this.page = 1;
        let data = await this.$httpN.postQ('mpb/mpbsaleb2c/list',{
          beginDate: this.datarange? this.datarange[0]: '',
          endDate: this.datarange? this.datarange[1]: '',
          platId: this.platId,
          orderNo: this.orderNo,
          originOrderNo: this.originOrderNo,
          page: this.page,
          limit: this.pageSize
        })
        this.tableData = data.list
        this.totalPage = data.totalCount
      },
      sizeChangeHandle(limit) {
        this.pageSize = limit;
        this.searchItem(true);
      },
      currentChangeHandle(page) {
        this.page = page;
        this.searchItem();
      },
      async saveForm(){
        if(!formUtil.verifyData(this.customForm, this.formVerify)) return;
        let postForm = {
          orderNo: this.customForm.orderNo,
          platId: this.customForm.platId,
          saleValueBd: this.customForm.saleValueBd,
          saleValue: this.customForm.saleValue,
          currencyType: this.customForm.currencyType,
          countryCode: this.customForm.countryCode,
          status: this.customForm.status,
          remark: this.customForm.remark,
          saleDate: this.customForm.saleDate,
          saleId: this.customForm.saleId
        }
        if(this.customForm.id) postForm.id = this.customForm.id;
        if(!await this.$httpN.postB('mpb/mpbsaleb2c/save', postForm,false)) return;
        this.customerDialog = false;
        formUtil.submitSuccess('保存成功');
        this.searchItem();
      },
      removeItem(id) {
        formUtil.submitConfirm('此操作将永久删除该记录, 是否继续?', async ()=> {
          if(!await this.$httpN.postB('mpb/mpbsaleb2c/delete', [id], false)) return;
          formUtil.submitSuccess('删除成功');
          this.searchItem(true)
        })
      },
      async updateB2C() {
        await this.$httpN.get('mpb/mpbsaleb2c/updateB2cList');
        formUtil.submitSuccess('更新成功');
      },
      uploadFile(e) {
        let file = e.target.files[0];
        var formData = new FormData();
        formData.append("file", file);
        formData.append("name", 'file');
        this.$httpN.upload('mpb/mpbsaleb2c/uploadExcel', formData).then((res) => {
          if(res.status === 200 && res.data.code === 0) {
            formUtil.submitSuccess('上传成功')
          }else{
            this.$message.error('上传文件出错,请重试')
          }
        })
      },
      async exportExcel() {
        if(!this.datarange[0] || !this.datarange[1]) return this.$message.error('请选择开始时间和结束时间')

        let data = await this.$httpN.get('mpb/mpbsaleb2c/export', {
          beginDate: this.datarange? this.datarange[0]: '',
          endDate: this.datarange? this.datarange[1]: '',
          platId: this.platId,
          orderNo: this.orderNo,
          originOrderNo: this.originOrderNo
        }, 'blob')

        this.downFile(data, `B2C订单.xls`);
      },
      downFile(blob, fileName) {
        if (window.navigator.msSaveOrOpenBlob) {
          navigator.msSaveBlob(blob, fileName);
        } else {
          var link = document.createElement('a');
          link.href = window.URL.createObjectURL(blob);
          link.download = fileName;
          link.click();
          window.URL.revokeObjectURL(link.href);
        }
      }
    }
  }
</script>

<style lang="scss" scoped>

  .form-wrapper .el-select.el-select--medium{
    width: 100%;
  }
  .form-wrapper{
    width: 70%;
    margin: 0 auto;
    min-width: 990px;
    padding: 70px;
    padding-top: 10px;
    padding-left:0;
    position:relative;
  }
  .status-line{
    position:fixed;
    top: 200px;
    right: 140px;
    height: 240px;
  }
  .notice{
    margin-top:10px;
    color:red;
    padding-left:120px;
  }
  .back-btn{
    position: fixed;
    top: 50px;
    left: 50px;
  }
  .file-upload-btn{
    position: absolute;
    width:  70px;
    height: 56px;
    right: 0;
    top: -20px;
    opacity: 0;
    cursor: pointer;
  }
</style>